import 'package:flutter_admin/api/odoo/dynamic_data_api.dart';
import 'package:flutter_admin/api/odoo/finished_in_scan_odoo_api.dart';
import 'package:flutter_admin/api/odoo/stock_move_line_odoo_api.dart';
import 'package:flutter_admin/api/odoo/stock_quant_odoo_api.dart';
import 'package:flutter_admin/generated/l10n.dart';
import 'package:flutter_admin/models/odoo/finish_in.dart';
import 'package:flutter_admin/models/odoo/stock_move_line.dart';
import 'package:flutter_admin/models/odoo/stock_quant.dart';
import 'package:flutter_admin/pages/common/cry/cry_button.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_input.dart';
import 'package:flutter/material.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_input_num.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_select.dart';
import 'package:flutter_admin/pages/common/cry/model/response_body_api.dart';
import 'package:flutter_admin/pages/common/cry/utils/cry_utils.dart';
import 'package:flutter_admin/pages/common/cry/utils/http_util.dart';
import 'package:flutter_admin/pages/common/cry/vo/select_option_vo.dart';
import 'package:flutter_admin/utils/eventbus.dart';
import 'package:flutter_admin/utils/store_util.dart';
import 'package:qrscan/qrscan.dart' as scanner;
import 'package:quiver/strings.dart';

class HWPacking extends StatefulWidget {
  HWPacking({Key? key,required this.id}) : super(key: key);

  String id;

  @override
  _HWPackingState createState() => _HWPackingState();
}

class _HWPackingState extends State<HWPacking> {
  final GlobalKey<FormState> formKey = GlobalKey<FormState>();
  final GlobalKey<ScaffoldState> scaffoldStateKey = GlobalKey<ScaffoldState>();
  String scan1 = '';
  String scan2 = '';
  var _subscription;
  bool isLoading = false;
  String passWord = '';
  FocusNode _focusNode = FocusNode();
  @override
  void initState() {
    super.initState();
    _subscription = EventBus.getSubscriber()
        .where((event) => event["key"] == "HWPacking")
        .listen(_onEnvent);
    _loadSelectVO();
  }

  @override
  void dispose() {
    _subscription.cancel();
    StoreUtil.write("key", "HWCheckDetail");
    super.dispose();
  }

  //处理扫码获得的code
  void _onEnvent(dynamic obj) async{
    try {
      formKey.currentState!.save();
      var scan = obj["scan"].toString();
      if(isBlank(scan1)){
        scan1 = scan;
      }else{
        scan2 = scan;
        if(scan1 != scan){
          isLoading= true;
          _focusNode.requestFocus();
        }
      }
      setState(() {});
    } catch (e) {
      print(e);
      // CryUtils.message(e.toString());
      return;
    }
  }

  _loadSelectVO() async {
    var res = await DynamicDataApi.getModels(model: "huawei.lock_pwd");
    if( res.success! ){
      passWord = res.data[0]["pwd"];
    }
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    var form = Form(
      key: formKey,
      child: Wrap(
        children: <Widget>[
          CryInput(
            label: '扫码对比值',
            enable: false,
            value: scan1,
          ),
          CryInput(
            label: '扫码对比值',
            enable: false,
            value: scan2,
          ),
        ],
      ),
    );

    var footerBar = ButtonBar(
      alignment: MainAxisAlignment.center,
      children: <Widget>[
        CryButton(
          label: "确定",
          onPressed: () {
            FormState form = formKey.currentState!;
            if (!form.validate()) {
              return;
            }
            form.save();
            if(isBlank(scan2)){
              CryUtils.message("请扫描内外码");
              return ;
            }
            StockQuantOdooApi.saveOrUpdate({
              'id':int.parse(widget.id),
              'is_packaging':'1',
              'internal_print_str': scan1,
              'exterior_print_str': scan2,
            }).then((ResponseBodyApi res) {
              if (!res.success!) {
                return;
              }
              Navigator.pop(context, true);
              CryUtils.message(S.of(context).saved);
            });
          },
          iconData: Icons.save,
        ),
        CryButton(
          label: S.of(context).cancel,
          onPressed: () {
            Navigator.pop(context);
          },
          iconData: Icons.cancel,
        )
      ],
    );
    var result = Scaffold(
      key: scaffoldStateKey,
      appBar: AppBar(
        title: Text("包装确认"),
      ),
      body: SingleChildScrollView(
        child: Column(
          children: [form],
        ),
      ),
      bottomNavigationBar: footerBar,
    );
    return Stack(
      alignment: Alignment.center,
      fit: StackFit.expand, //未定位widget占满Stack整个空间
      children: <Widget>[
        // Positioned(
        //   left: 18.0,
        //   child: Text("I am Jack"),
        // ),
        SizedBox(
          width: 650,
          height: 650,
          child: result,
        ),
        isLoading
            ? Positioned(
          // top: 18.0,
          child: Container(
            // width: 800,
            // height: 800,
            color: Colors.black87,
            child: Center(
              child: Container(
                width: 200,
                color: Colors.white,
                child: TextFormField(
                  focusNode: _focusNode,
                  style: TextStyle(color: Colors.black),
                  decoration: InputDecoration(
                    labelText: '密码',
                    contentPadding: EdgeInsets.symmetric(horizontal: 10),
                  ),
                  // controller: TextEditingController(text: passWord),
                  onChanged: (v) {
                    if(passWord == v){
                      isLoading = false;
                      scan1 = '';
                      scan2 = '';
                      setState(() {});
                    }
                  },
                ),
                // child: CryInput(
                // label: '密码',
                // width: 200,
                // onChange: (v) {
                //   if(passWord == v){
                //     isLoading = false;
                //     scan1 = '';
                //     scan2 = '';
                //     setState(() {});
                //   }
                // },
              ),
            ),
          ),
        )
            : Container(),
      ],
    );
  }

}
